// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Win32.SafeHandles;
using System.Security.Cryptography.EcDsa.Tests;
using Xunit;

namespace System.Security.Cryptography.Cng.Tests
{
    public static class OpenTests
    {
        [Fact]
        public static void OpenFromHandle()
        {
            byte[] blobOriginal = TestData.Key_ECDiffieHellmanP256;
            using (CngKey keyOriginal = CngKey.Import(blobOriginal, CngKeyBlobFormat.GenericPublicBlob))
            {
                SafeNCryptKeyHandle keyHandle = keyOriginal.Handle;
                Assert.NotNull(keyHandle);
                using (CngKey key = CngKey.Open(keyHandle, CngKeyHandleOpenOptions.EphemeralKey))
                {
                    keyHandle.Dispose();

                    Assert.Equal(keyOriginal.Algorithm, key.Algorithm);
                    Assert.Equal(keyOriginal.AlgorithmGroup, key.AlgorithmGroup);
                    Assert.Equal(keyOriginal.ExportPolicy, key.ExportPolicy);
                    Assert.Equal(keyOriginal.IsEphemeral, key.IsEphemeral);
                    Assert.Equal(keyOriginal.IsMachineKey, key.IsMachineKey);
                    Assert.Equal(keyOriginal.KeyName, key.KeyName);
                    Assert.Equal(keyOriginal.KeySize, key.KeySize);
                    Assert.Equal(keyOriginal.KeyUsage, key.KeyUsage);
                    Assert.Equal(keyOriginal.ParentWindowHandle, key.ParentWindowHandle);
                    Assert.Equal(keyOriginal.Provider, key.Provider);

                    CngUIPolicy policy = key.UIPolicy;
                    Assert.Equal(keyOriginal.UIPolicy.CreationTitle, policy.CreationTitle);
                    Assert.Equal(keyOriginal.UIPolicy.Description, policy.Description);
                    Assert.Equal(keyOriginal.UIPolicy.FriendlyName, policy.FriendlyName);
                    Assert.Equal(keyOriginal.UIPolicy.UseContext, policy.UseContext);
                    Assert.Equal(keyOriginal.UIPolicy.ProtectionLevel, policy.ProtectionLevel);

                    Assert.Equal(keyOriginal.UniqueName, key.UniqueName);

                    byte[] reExported = key.Export(CngKeyBlobFormat.GenericPublicBlob);
                    Assert.Equal<byte>(blobOriginal, reExported);
                }
            }
        }
    }
}
